//
//  SXReadRecommendDetailViewController.m
//  ShiXun
//
//  Created by lanou on 15/10/29.
//  Copyright © 2015年 张琪. All rights reserved.
//

#import "SXReadRecommendDetailViewController.h"
#import "SXRequestManager.h"
#import "UIView+UIView.h"
#import "UMSocial.h"
#import "SXCollectionManager.h"
#import "SXRefreshView.h"

@interface SXReadRecommendDetailViewController ()

@property (nonatomic, strong) UIWebView *detailWebView;
@property (nonatomic, copy) NSString *titleStr;
@property (nonatomic, copy) NSString *source_url;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) SXRefreshView *refreshingView;

@end

@implementation SXReadRecommendDetailViewController

- (UIWebView *)detailWebView
{
    if (!_detailWebView) {
        _detailWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 104)];
        _detailWebView.backgroundColor = [UIColor whiteColor];        
    }
    return _detailWebView;
}

- (UILabel *)titleLabel
{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, kScreenWidth, 44)];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLabel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithWhite:0.912 alpha:1.000];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.hidden = YES;
    
    [self.view addSubview:self.titleLabel];
    
    UIButton *backButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    backButton.frame = CGRectMake(10, kScreenHeight - 32, 25, 25);
    [backButton setBackgroundImage:[UIImage imageNamed:@"SX-yuedufanhui"] forState:(UIControlStateNormal)];
    [backButton addTarget:self action:@selector(doBack) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:backButton];
    
    UIButton *shareButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    shareButton.frame = CGRectMake(kScreenWidth - 50, kScreenHeight - 32, 25, 25);
    [shareButton setBackgroundImage:[UIImage imageNamed:@"SX-yuedushare"] forState:(UIControlStateNormal)];
    [shareButton addTarget:self action:@selector(share:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:shareButton];
    
    UIButton *collectionButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    collectionButton.selected = [SXCollectionManager checkCollectionWithTableName:@"read" urlID:_docid];
    collectionButton.frame = CGRectMake(kScreenWidth - 100, kScreenHeight - 32, 25, 25);
    [collectionButton setBackgroundImage:[UIImage imageNamed:@"SX-yuedushoucang2"] forState:(UIControlStateNormal)];
    [collectionButton setBackgroundImage:[UIImage imageNamed:@"SX-yuedushoucang1"] forState:(UIControlStateSelected)];
    [collectionButton addTarget:self action:@selector(collectionRead:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:collectionButton];
    
    [self.view addSubview:self.detailWebView];
    [self requestData];
    
    _refreshingView = [[SXRefreshView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:_refreshingView];
}

// 网络请求
- (void)requestData
{
    NSString *urlString = [kReadRecommendDetailURLString stringByAppendingFormat:@"%@/full.html", _docid];
    [SXRequestManager requestWithType:GET urlString:urlString parDic:nil finish:^(NSData *data) {
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves |NSJSONReadingMutableContainers) error:nil];
        NSDictionary *dic = dict[_docid];
        self.titleStr = dic[@"title"];
        self.source_url = dic[@"source_url"];
        self.titleLabel.text = self.titleStr;
        
        NSString *htmlString = dic[@"body"];
        NSArray *imgArray = dic[@"img"];
        htmlString = [self.view webViewHtmlString:htmlString imgArray:imgArray];
        [self.detailWebView loadHTMLString:htmlString baseURL:nil];
        [_refreshingView removeFromSuperview];
        
    } error:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

// 返回
- (void)doBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

// 分享
- (void)share:(UIButton *)button
{
    // 分享后是否提示（YES是不提示）
    [UMSocialConfig setFinishToastIsHidden:NO position:(UMSocialiToastPositionCenter)];
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"5632c41ce0f55a17390010c1"
                                      shareText:[NSString stringWithFormat:@"更多精彩内容等你来看，点击进入详情：%@",self.source_url]
                                     shareImage:[UIImage imageNamed:@"icon.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToDouban,UMShareToRenren,UMShareToTencent,nil]
                                       delegate:nil];
}

// 收藏
- (void)collectionRead:(UIButton *)button
{
    button.selected = !button.selected;
    NSString *str = @"收藏成功";
    if (!button.selected) {
        str = @"取消收藏成功";
    }
    [SXCollectionManager collectionDataWithTableName:@"read" title:self.titleStr urlID:_docid isCollection:button.selected finish:^(BOOL isSuccessed) {
        if (isSuccessed) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
            [alertView show];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [alertView dismissWithClickedButtonIndex:0 animated:NO];
            });
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
